/**
 * 应用状态管理Store
 * 统一管理应用的部署状态和生成状态
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  DEPLOY_STATUS,
  GENERATE_STATUS,
  DEPLOY_STATUS_TEXT,
  GENERATE_STATUS_TEXT,
  DEPLOY_STATUS_COLOR,
  GENERATE_STATUS_COLOR,
  type DeployStatus,
  type GenerateStatus
} from '@/constants/appStatus'

export interface AppStatusInfo {
  id: string | number
  deployStatus: DeployStatus
  generateStatus: GenerateStatus
  deployedTime?: string
  deployKey?: string
  currentTaskId?: string
  userId?: number
  lastUpdated: number
}

export const useAppStatusStore = defineStore('appStatus', () => {
  // 应用状态缓存
  const appStatusMap = ref<Map<string | number, AppStatusInfo>>(new Map())

  // 获取应用状态信息
  const getAppStatus = (appId: string | number): AppStatusInfo | null => {
    return appStatusMap.value.get(appId) || null
  }

  // 设置应用状态信息
  const setAppStatus = (appId: string | number, statusInfo: Partial<AppStatusInfo>) => {
    const existing = appStatusMap.value.get(appId)
    const updated: AppStatusInfo = {
      id: appId,
      deployStatus: DEPLOY_STATUS.NOT_DEPLOYED,
      generateStatus: GENERATE_STATUS.NOT_GENERATED,
      lastUpdated: Date.now(),
      ...existing,
      ...statusInfo,
    }
    appStatusMap.value.set(appId, updated)
  }

  // 从AppVO更新状态
  const updateStatusFromAppVO = (app: API.AppVO) => {
    if (!app.id) return

    // 计算部署状态
    let deployStatus: DeployStatus
    if (typeof app.deployStatus === 'number') {
      deployStatus = app.deployStatus as DeployStatus
    } else if (app.deployedTime) {
      // 向后兼容：基于 deployedTime 判断
      deployStatus = DEPLOY_STATUS.DEPLOYED
    } else {
      deployStatus = DEPLOY_STATUS.NOT_DEPLOYED
    }

    // 计算生成状态
    const generateStatus = (app.generateStatus as GenerateStatus) || GENERATE_STATUS.NOT_GENERATED

    setAppStatus(app.id, {
      deployStatus,
      generateStatus,
      deployedTime: app.deployedTime,
      deployKey: app.deployKey,
      currentTaskId: app.currentTaskId,
      userId: app.userId,
    })
  }  // 更新部署状态
  const updateDeployStatus = (appId: string | number, deployStatus: DeployStatus, deployKey?: string, deployedTime?: string) => {
    setAppStatus(appId, {
      deployStatus,
      deployKey,
      deployedTime: deployedTime || (deployStatus === DEPLOY_STATUS.DEPLOYED ? new Date().toISOString() : undefined)
    })
  }

  // 更新生成状态
  const updateGenerateStatus = (appId: string | number, generateStatus: GenerateStatus, currentTaskId?: string) => {
    setAppStatus(appId, { generateStatus, currentTaskId })
  }

  // 移除应用状态（应用被删除时）
  const removeAppStatus = (appId: string | number) => {
    appStatusMap.value.delete(appId)
  }

  // 清空所有状态（登出时）
  const clearAllStatus = () => {
    appStatusMap.value.clear()
  }

  // 计算属性：获取部署状态相关信息
  const getDeployStatusInfo = (appId: string | number) => {
    return computed(() => {
      const status = getAppStatus(appId)
      if (!status) return null

      const deployStatus = status.deployStatus
      return {
        status: deployStatus,
        text: DEPLOY_STATUS_TEXT[deployStatus],
        color: DEPLOY_STATUS_COLOR[deployStatus],
        isDeployed: deployStatus === DEPLOY_STATUS.DEPLOYED,
        isDeploying: deployStatus === DEPLOY_STATUS.DEPLOYING,
        canDeploy: deployStatus !== DEPLOY_STATUS.DEPLOYING, // 允许重新部署，只有部署中时不能部署
        deployKey: status.deployKey,
        deployedTime: status.deployedTime,
      }
    })
  }

  // 计算属性：获取生成状态相关信息
  const getGenerateStatusInfo = (appId: string | number) => {
    return computed(() => {
      const status = getAppStatus(appId)
      if (!status) return null

      const generateStatus = status.generateStatus
      return {
        status: generateStatus,
        text: GENERATE_STATUS_TEXT[generateStatus],
        color: GENERATE_STATUS_COLOR[generateStatus],
        isGenerating: generateStatus === GENERATE_STATUS.GENERATING,
        isCompleted: generateStatus === GENERATE_STATUS.COMPLETED,
        isFailed: generateStatus === GENERATE_STATUS.FAILED,
        isInterrupted: generateStatus === GENERATE_STATUS.INTERRUPTED,
        currentTaskId: status.currentTaskId,
      }
    })
  }

  // 批量更新多个应用状态（用于列表页面）
  const batchUpdateFromAppList = (appList: API.AppVO[]) => {
    appList.forEach(app => {
      updateStatusFromAppVO(app)
    })
  }

  // 获取指定应用的完整状态信息
  const getCompleteStatusInfo = (appId: string | number) => {
    return computed(() => {
      const deployInfo = getDeployStatusInfo(appId).value
      const generateInfo = getGenerateStatusInfo(appId).value

      return {
        deploy: deployInfo,
        generate: generateInfo,
        hasStatus: deployInfo !== null && generateInfo !== null,
      }
    })
  }

  return {
    // 数据
    appStatusMap,

    // 基础方法
    getAppStatus,
    setAppStatus,
    updateStatusFromAppVO,
    updateDeployStatus,
    updateGenerateStatus,
    removeAppStatus,
    clearAllStatus,
    batchUpdateFromAppList,

    // 计算属性方法
    getDeployStatusInfo,
    getGenerateStatusInfo,
    getCompleteStatusInfo,
  }
})
